package game.view.screen 
{
	import flash.geom.Point;
	import game.ApplicationFacade;
	import game.model.building.vo.BuildingVO;
	import game.utils.collision.Collision;
	import game.utils.touch.TouchManager;
	import game.view.event.BuildingEvent;
	import game.view.screen.components.BuildingComponent;
	import starling.display.DisplayObject;
	import starling.display.Sprite;
	import starling.events.Touch;
	import starling.events.TouchEvent;
	import starling.events.TouchPhase;
	
	/**
	 * ...
	 * @author Thot
	 */
	
	public class GameBoardScreen extends Sprite
	{
		
		private var _elements:Vector.<DisplayObject>;
		private var _touchManager:TouchManager;
		
		public function GameBoardScreen()
		{
		}
		
		public function init():void
		{
			_elements = new Vector.<DisplayObject>();	
			addEventListener( TouchEvent.TOUCH, touchHandler );
		}
		
		private function touchHandler(event:TouchEvent):void
		{
			var collide:Vector.<DisplayObject> = null;
			var touches:Vector.<Touch> = event.getTouches(this, TouchPhase.ENDED);
			var touchA:Touch = null;
			var locA:Point = null;
			
			if ( touches.length == 1 )
			{
				touchA = touches[0];
				locA = touchA.getLocation(this);
				collide = Collision.hitTest( _elements, locA.x, locA.y, 5, 5 );
				
				if ( collide.length > 0 )
				{
					dispatchEvent( new BuildingEvent( BuildingEvent.TOUCH_BUILDING, collide[0].name ) );
				}
			}
		}
		
		public function addBuilding( value:BuildingComponent ):void
		{
			_elements.push(value);
			addChild( value );
		}
		
		public function removeBuilding( value:BuildingComponent ):void
		{
			var index:int = _elements.indexOf(value);
			
			if ( index > -1 )
			{
				_elements.splice( index, 1 );
			}
		}
		
		public function getBuildingByName( value:String ):BuildingComponent
		{
			return getChildByName(value) as BuildingComponent;
		}
		
		public function clean():void
		{
			while ( _elements.length > 0 )
			{
				_elements.shift();
			}
		}
		
		public function actualizeBuildingState(vo:BuildingVO):void 
		{
			var building:BuildingComponent = getBuildingByName(vo.name);
			
			if ( building == null )
				return;
				
			building.increasing = vo.isIncreasing();
			building.progression = vo.timeLeft;
		}
		
	}

}